package pe.edu.upc.jtigers.svpn.web.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.util.WebUtils;
import pe.edu.upc.jtigers.svpn.domain.model.Usuario;
import pe.edu.upc.jtigers.svpn.domain.service.UsuarioService;
import pe.edu.upc.jtigers.svpn.web.common.RequestMappingConstant;
import pe.edu.upc.jtigers.svpn.web.common.WebParameterConstant;

@Controller
public class LoginController {

	@Autowired
	private UsuarioService usuarioService;

	@RequestMapping(value = RequestMappingConstant.LOGIN)
	@ResponseStatus(value = HttpStatus.OK)
	public @ResponseBody
	Usuario login(@RequestBody Usuario usuario, HttpServletRequest request) {

		usuario = usuarioService.iniciarSesion(usuario);
		WebUtils.setSessionAttribute(request,
				WebParameterConstant.SESSION_USER, usuario);
		System.out.println("Login " + usuario);
		return usuario;
	}

	@RequestMapping(value = RequestMappingConstant.LOGOUT)
	public String logout(HttpServletRequest request) {
		request.getSession(true).removeAttribute(
				WebParameterConstant.SESSION_USER);
		return "redirect:inicio.html";
	}
}
